//
//  MediaInfoController.swift
//  SmallParts
//
//  Created by 航汇聚 on 2019/11/12.
//  Copyright © 2019 BellaZhou. All rights reserved.
//

import UIKit

class MediaInfoController: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var coverImgView: UIImageView!
    @IBOutlet weak var nickNameLabel: UILabel!
    @IBOutlet weak var issnNumberLabel: UILabel!
    @IBOutlet weak var cnNumberLabel: UILabel!
    @IBOutlet weak var publishPeriodLabel: UILabel!
    @IBAction func valueChanged(_ sender: UISegmentedControl) {
        switch sender.selectedSegmentIndex {
        case 0:
            break
        default:
            let numInfoObj = self.mediaResultObj?.num![0]
            self.requestNumInfo(id: "\(numInfoObj!.gch5)|\(numInfoObj!.year)|\(numInfoObj?.num.components(separatedBy: ",").last ?? "")", pageIndex: self.numInfoSearchPageIndex, pageSize: self.numInfoSearchPageSize)
        }
        self.selectedSegmentIndex = sender.selectedSegmentIndex
    }
    var numInfoSearchPageIndex = 0
    let numInfoSearchPageSize = 1000
    var selectedSegmentIndex: Int = 0 {
        didSet {
            self.tableView.reloadData()
        }
    }
    var mediaResultObj: GetInfoResultMediaModel? {
        didSet {
            if (mediaResultObj != nil) {
                configTableHeader(mediaObj: self.mediaResultObj!.obj!)
                self.tableView.reloadData()
            }
        }
    }
    var numInfoList: [NumInfoItemModel]? {
        didSet {
            if numInfoList!.count != 0 {
                self.tableView.reloadData()
            }
        }
    }
    var indexOfSelectYear: Int = 0
    var indexOfSelectPeriod: Int = 0
    let upload = UploadingData.init()
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }
}
extension MediaInfoController {
    func configTableHeader(mediaObj: MediaObjModel) {
        DispatchQueue.global().sync {
            let imgURL = mediaObj.mediapic
            if (imgURL != nil) {
                let downloadTask = URLSession.shared.dataTask(with: imgURL!) { (data, response, error) in
                    DispatchQueue.main.async {
                        self.coverImgView.image = UIImage(data: data!)
                    }
                }
                downloadTask.resume()
            }
        }
        self.nickNameLabel.text = "曾用名:\(mediaObj.oldname!.isEmpty ? "暂无" : mediaObj.oldname!)"
        self.issnNumberLabel.text = "ISSN号:\(mediaObj.issn!)"
        self.cnNumberLabel.text = "CN号:\(mediaObj.cn!)"
        self.publishPeriodLabel.text = "出版周期:\(mediaObj.periodtype!)"
    }
    func requestNumInfo(id: String, pageIndex: Int, pageSize:Int) {
        let upload = UploadingData.init()
        upload.uploadData("http://api.cqvip.com/qikanapp/GetSearch.ashx", "PageIndex=\(pageIndex)&PageSize=\(pageSize)&id=\(id)", .post)
        upload.success = { (data, urlString) -> () in
             let result = try? JSONDecoder().decode(NumInfoDictModel.self, from: data!)
            self.numInfoList = result?.result.list
            self.tableView.reloadData()
        }
    }
}
extension MediaInfoController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch self.selectedSegmentIndex {
        case 0:
            return 3
        default:
            return self.numInfoList == nil ? 1 : 1+(self.numInfoList?.count)!
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch self.selectedSegmentIndex {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "detailCell", for: indexPath) as! DetailCell
            if (mediaResultObj != nil) {
                switch indexPath.row {
                case 0:
                    let cell = tableView.dequeueReusableCell(withIdentifier: "infoCell", for: indexPath) as! InfoCell
                    let mediaObj = self.mediaResultObj!.obj!
                    cell.titleView.titleLabel.text = "期刊信息"
                    cell.competentUnitLabel.text = mediaObj.organizers!.isEmpty ? "暂无" : mediaObj.organizers!
                    cell.hostUnitLabel.text = mediaObj.publisher!.isEmpty ? "暂无" : mediaObj.publisher!
                    cell.cheifEditorLabel.text = mediaObj.headeditor!.isEmpty ? (mediaObj.editor!.isEmpty ? "暂无信息" : mediaObj.editor!) : mediaObj.headeditor!
                    cell.addressLabel.text = mediaObj.address!.isEmpty ? "暂无" : mediaObj.address!
                    cell.postalCodeLabel.text = mediaObj.postcode!.isEmpty ? "暂无" : mediaObj.postcode!
                    cell.phoneLabel.text = mediaObj.tel!.isEmpty ? "暂无" : mediaObj.tel!
                    cell.emailLabel.text = mediaObj.email!.isEmpty ? "暂无" : mediaObj.email!
                    return cell
                case 1:
                    cell.titleView.titleLabel.text = "期刊简介"
                    cell.infoLabel.text = (self.mediaResultObj?.obj?.introduction!.isEmpty)! ? "暂无介绍" : self.mediaResultObj?.obj?.introduction!
                    break
                default:
                    cell.titleView.titleLabel.text = "收录情况"
                    cell.infoLabel.text = (self.mediaResultObj?.obj?.lngrangeid!.isEmpty)! ? "暂无介绍" : self.mediaResultObj?.obj?.lngrangeid!.replacingOccurrences(of: ",", with: "\n")
                    break
                }
            }
            return cell
        default:
            switch indexPath.row {
            case 0:
                let cell = tableView.dequeueReusableCell(withIdentifier: "periodcalHeaderCell", for: indexPath) as! PeriodcalHeaderCell
                let numInfoObj = self.mediaResultObj?.num![self.indexOfSelectYear]
                cell.titleLabel.text = "\(numInfoObj!.year)年第\(numInfoObj?.num.components(separatedBy: ",")[self.indexOfSelectPeriod] ?? "")期"
                cell.periodicalNumArray = self.mediaResultObj?.num
                cell.indexOfSelectYear = self.indexOfSelectYear
                cell.indexOfSelectPeriod = self.indexOfSelectPeriod
                cell.passYearAndPeriodBlock = { (year, indexOfYear, period, indexOfPeriod) in
                    self.requestNumInfo(id: "\(numInfoObj!.gch5)|\(year)|\(period)", pageIndex: self.numInfoSearchPageIndex, pageSize: self.numInfoSearchPageSize)
                    self.indexOfSelectPeriod = indexOfPeriod
                    self.indexOfSelectYear = indexOfYear
                }
                return cell
            default:
                let cell = tableView.dequeueReusableCell(withIdentifier: "periodicalCell", for: indexPath) as! PeriodicalCell
                let numInfoItem = self.numInfoList?[indexPath.row-1]
                cell.titleLabel.text = numInfoItem?.Title
                cell.writerLabel.text = numInfoItem!.Writer.count == 0 ? "" : "作者:\(numInfoItem!.Writer)"
                cell.indexofPageLabel.text = (numInfoItem?.Beginpage.count != 0 && numInfoItem?.Endpage.count != 0) ? "\(numInfoItem!.Beginpage)-\(numInfoItem!.Endpage)" : (numInfoItem?.Endpage.count == 0 ? numInfoItem?.Beginpage : numInfoItem?.Endpage)
                return cell
            }
        }
    }
}
extension MediaInfoController {
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toArticalInfoVC" {
            let articalInfoController = segue.destination as! ArticalInfoController
            let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)! as NSIndexPath
            let numInfoObj = self.numInfoList?[indexPath.row - 1]
            upload.uploadData("\(apiHostURL)\(apiPath)\(GetInfoNew)", "key=\((numInfoObj?.Lngid)!)&type=article", .post)
            upload.success = { (data, urlStr) in
                let result = try? JSONDecoder().decode(GetInfoDictArticalModel.self, from: data!)
                articalInfoController.articalInfoObj = result?.result.obj!
            }
            articalInfoController.view.backgroundColor = UIColor.white
            articalInfoController.hidesBottomBarWhenPushed = true
        }
    }
}
class InfoCell: UITableViewCell {
    @IBOutlet weak var titleView: TitleView!
    @IBOutlet weak var competentUnitLabel: UILabel!
    @IBOutlet weak var hostUnitLabel: UILabel!
    @IBOutlet weak var cheifEditorLabel: UILabel!
    @IBOutlet weak var addressLabel: UILabel!
    @IBOutlet weak var postalCodeLabel: UILabel!
    @IBOutlet weak var phoneLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
}
class DetailCell: UITableViewCell {
    @IBOutlet weak var titleView: TitleView!
    @IBOutlet weak var infoLabel: UILabel!
}
class PeriodcalHeaderCell: UITableViewCell {
    var periodicalNumArray: [MediaNumModel]?
    var passYearAndPeriodBlock: passYearAndPeriod?
    var indexOfSelectYear: Int?
    var indexOfSelectPeriod: Int?
    @IBOutlet weak var titleLabel: UILabel!
    @IBAction func changePeriodicalValue(_ sender: UIButton) {
        let pickerPeriodicalView = PickerPeriodView.loadFromNib()
        pickerPeriodicalView.indexOfSelectYear = self.indexOfSelectYear!
        pickerPeriodicalView.indexOfSelectPeriod = self.indexOfSelectPeriod!
        pickerPeriodicalView.periodicalNumArray = periodicalNumArray
        pickerPeriodicalView.frame = UIApplication.shared.keyWindow!.bounds
        UIApplication.shared.keyWindow?.addSubview(pickerPeriodicalView)
        pickerPeriodicalView.passYearAndPeriodBlock = { (year, indexOfYear, period, indexOfPeriod) in
            if self.passYearAndPeriodBlock != nil {
                self.passYearAndPeriodBlock!(year, indexOfYear, period, indexOfPeriod)
            }
        }
    }
}
class PeriodicalCell: UITableViewCell {
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var writerLabel: UILabel!
    @IBOutlet weak var indexofPageLabel: UILabel!
}
